package com.sjyl.kaoshitong.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.orhanobut.hawk.Hawk;
import com.orhanobut.logger.Logger;
import com.sjyl.kaoshitong.R;
import com.sjyl.kaoshitong.activities.QuestionDetailActivity;
import com.sjyl.kaoshitong.adapter.QARecyclerViewAdapter;
import com.sjyl.kaoshitong.beans.ApiResponse;
import com.sjyl.kaoshitong.beans.QuestionItem;
import com.sjyl.kaoshitong.beans.Recontent;
import com.sjyl.kaoshitong.itemdecoreations.SpacesItemDecoration;
import com.sjyl.kaoshitong.util.APIUtils;
import com.sjyl.kaoshitong.util.Cheeses;
import com.sjyl.kaoshitong.util.OKHttpUtil;
import com.sjyl.kaoshitong.util.PreferencesKeyUtil;
import com.sjyl.kaoshitong.util.ToastUtil;
import com.sjyl.kaoshitong.util.Utility;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import tr.xip.errorview.ErrorView;

/**
 * Created by ChangerLow on 15/6/22.
 * Email: changerlow@qq.com
 */
public class QARewardFragment extends Fragment implements QARecyclerViewAdapter.ViewHolder.MyOnItemClickListener {
    private static final String TAG = "QARewardFragment";
    private SwipeRefreshLayout swipeRefreshLayout;
    private RecyclerView recyclerView;
    private RecyclerView.LayoutManager layoutManager;
    private QARecyclerViewAdapter adapter;
    private List<QuestionItem> dataList;
    private LinearLayout refreshView;
    private ErrorView errorView;
    private LinearLayout emptyView;
    private OkHttpClient okHttpClient;
    private Gson gson = new Gson();
    private String pid;
    private int currentPage = 1;
    private int tag = 0;
    private String funName;
    boolean isVisible = false;
    private boolean initView = false;
    private boolean loadData = false;

    public static QARewardFragment newInstance(int arg) {
        QARewardFragment fragment = new QARewardFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("tag", arg);
        fragment.setArguments(bundle);
        return fragment;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Logger.i(TAG, tag + "=======onCreate");
        Hawk.init(getActivity());
        tag = getArguments().getInt("tag");
        if (tag == 0) {
            funName = APIUtils.URL_FUNCTION_GET_NO_FINISH_QA;
        } else if (tag == 1) {
            funName = APIUtils.URL_FUNCTION_GET_HIGH_AWARD_QA;
        } else if (tag == 2) {
            funName = APIUtils.URL_FUNCTION_GET_FINISH_QA;
        }
        Logger.d(TAG, tag+"===========keyword "+Hawk.get("key_word", ""));

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Logger.i(TAG, tag+"========onCreateView"+isVisible);
        View rootView = inflater.inflate(R.layout.fragment_qa_reward_layout, container, false);
        swipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe_refresh_layout);
        swipeRefreshLayout.setColorSchemeResources(R.color.color_primary, R.color.color_primary_dark);
        refreshView = (LinearLayout) rootView.findViewById(R.id.refresh_layout);
        emptyView = (LinearLayout)rootView.findViewById(R.id.emptyview);
        errorView = (ErrorView) rootView.findViewById(R.id.error_view);
        recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerview);
        layoutManager = new LinearLayoutManager(getActivity()) {
            @Override
            protected int getExtraLayoutSpace(RecyclerView.State state) {
                return 300;
            }
        };
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addItemDecoration(new SpacesItemDecoration(Utility.dp2px(getActivity(), 8)));
        dataList = new ArrayList<>();
        adapter = new QARecyclerViewAdapter(dataList);
        recyclerView.setAdapter(adapter);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                List<String> addOnData = Cheeses.randomList(5);
            }
        });
        adapter.setOnItemClickListener(this);
        okHttpClient = OKHttpUtil.getOkHttpClient(getActivity());
        initView = true;
        return rootView;
    }

    @Override
    public void OnItemClick(View view, int position) {
        Intent intent = new Intent(getActivity(), QuestionDetailActivity.class);
        intent.putExtra("id", "1111");
        getActivity().startActivity(intent);
        getActivity().overridePendingTransition(R.anim.slide_in_from_right, R.anim.do_nothing);
    }


    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Logger.i(TAG, tag+"=======onViewCreated");

    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Logger.i(TAG, tag + "=======onActivityCreated");
        showProgress();
        //getData(1);
        if (getUserVisibleHint() && isVisible() && initView) {
            getData(1);
        }
    }

    private void loadData(){
        getData(1);
    }

    private void getData(int page) {
        loadData = true;
        RequestBody body = new FormEncodingBuilder().add("funName", APIUtils.URL_FUNCTION_GET_NO_FINISH_QA).add("departId", "1").add("userId", Hawk.get(PreferencesKeyUtil.KEY_USER_ID, "")).add("keyWord", Hawk.get(PreferencesKeyUtil.KEY_KEY_WORD, "")).build();
        //.add("catalogId", pid).add("funpage", String.valueOf(page)).build();
        Request request = new Request.Builder().url(APIUtils.BASE_URL).post(body).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            Handler handler = new Handler(getActivity().getMainLooper());

            @Override
            public void onFailure(Request request, IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        showErrorview();
                    }
                });
            }

            @Override
            public void onResponse(Response response) throws IOException {
                String body = response.body().string();
                Logger.json(TAG, body);
                Type type = new TypeToken<ApiResponse<QuestionItem>>() {
                }.getType();
                final ApiResponse<QuestionItem> apiResponse = gson.fromJson(body, type);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (!apiResponse.getRecode().equals("2000")) {
                            ToastUtil.SnackerShow(getActivity(), getActivity().getString(R.string.get_data_error));
                        } else {
                            Recontent<QuestionItem> recontent = apiResponse.getRecontent();
                            if (apiResponse.getRecontent() == null) {
                                showEmptyView();
                                return;
                            }
                            List<QuestionItem> list = recontent.getRelist();
                            if (list.size() == 0) {
                                showEmptyView();
                                return;
                            }
                            Logger.d(TAG, "=========recode:" + " relist size:" + list.size());
                            showContent();
                        }
                    }
                });
            }
        });
    }

    private void showProgress() {
        emptyView.setVisibility(View.GONE);
        refreshView.setVisibility(View.VISIBLE);
        swipeRefreshLayout.setVisibility(View.GONE);
        errorView.setVisibility(View.GONE);
    }

    private void showContent() {
        emptyView.setVisibility(View.GONE);
        refreshView.setVisibility(View.GONE);
        swipeRefreshLayout.setVisibility(View.VISIBLE);
        errorView.setVisibility(View.GONE);
    }


    private void showErrorview() {
        emptyView.setVisibility(View.GONE);
        refreshView.setVisibility(View.GONE);
        swipeRefreshLayout.setVisibility(View.GONE);
        errorView.setVisibility(View.VISIBLE);

    }

    private void showEmptyView(){
        refreshView.setVisibility(View.GONE);
        swipeRefreshLayout.setVisibility(View.GONE);
        errorView.setVisibility(View.GONE);
        emptyView.setVisibility(View.VISIBLE);
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        Logger.i(TAG, tag + "=====setUserVisibleHint " + isVisibleToUser);
        isVisible = isVisibleToUser;
        if ( isVisible && isVisible() && initView && !loadData){
            loadData();
        }
    }
}
